const $ = layui.jquery;
let table=layui.table;
let laydate=layui.laydate;
let form=layui.form;
let layer=layui.layer;
let upload=layui.upload;
$(()=> {
//     渲染账号过期，权限过期，上次登录的日期时间
    laydate.render({
        elem:"[name=userExpireTime]",
        type:"datetime"
    })
    laydate.render({
        elem:"[name=credExpireTime]",
        type:"datetime",
    })
    laydate.render({
        elem:"[name=lastLoginTime]",
        type:"datetime",
    })

//     渲染图片上传
    upload.render({
        elem: '#avatar-upload-btn',
        url: ctx+'/sys/api/v1/upload/image',
        data:{//传的数据,这个type是自己起的名字，在后面会用到
            type:"admin_avatar",
        },
        exts:'jpg|png|gif|bmp|jpeg|svg', //上传的类型
        size:1024,
        done: function(resp){//上传完成，响应200状态码进入
            let url =ctx+"/assets/"+resp.data;
            $(".avatar-preview").css("background-image","url("+url+")");
            sessionStorage.setItem("admin_avatar",resp.data);//将图片地址存到会话存储域
        },
        error: function(){
            layer.msg("上传图片失败");
        },

    });
//     自定义验证规则,key为表单元素的name
    form.verify({
        username:function (value,elem){
            if(value.length<3||value.length>20){
                return "管理名长度必须介于3~20位之间";
            }
        }
    })




})
// 点击提交按钮后的异步提交操作
function doSubmit(cb){
    let pass=form.validate("#add-form")//参数验证
    if(!pass){
        return;
    }
    // 验证通过，向后台发请求
    const url=ctx+"/sys/api/v1/admin";
    let formData = form.val("add-form");//参数为过滤器
    let avatarUrl=sessionStorage.getItem("admin_avatar");
    if(avatarUrl){
        formData.avatarUrl=avatarUrl;
    }
    // 将locked字符串转换成布尔值
    if(formData.locked === "是"){
        formData.locked = true;
    }else if(formData.locked === "否"){
        formData.locked = false;
    }else{
        formData.locked = null;
    }
    $.ajax({
        url,
        method:"post",
        data: formData,
        success(resp){
            if(resp.success){
                if(typeof cb==="function"){
                    cb(resp.success)
                }
            }
        },error(resp){
            let json = resp.responseJSON;
            let msg=json.msg||"新增会员异常";
            layer.msg(msg);
        }
    })


}